package com.tg.message.msg;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.base.MessageFilterBean;
import com.appbase.custom.constant.EventConstants;
import com.base.BaseFragment;
import com.demo.view.PullLoadMoreRecyclerView;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.cloud.message.CloudMessage;
import com.tange.core.cloud.message.Message;
import com.tange.core.cloud.message.MessageByPagination;
import com.tange.core.cloud.message.MessageCategory;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.helper.LogoutDialogHelper;
import com.tg.data.bean.DeviceItem;
import com.tg.data.http.entity.WheelData;
import com.tg.message.R;
import com.tg.message.adapter.MessageAdapter;
import com.tg.message.adapter.MessageDateAdapter;
import com.tg.message.adapter.MessageDeviceAdapter;
import com.tg.message.adapter.MessageEventAdapter;
import com.tg.message.adapter.MessageFilterAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import io.reactivex.disposables.Disposable;

public class MessageFragment extends BaseFragment implements PullLoadMoreRecyclerView.PullLoadMoreListener {
    private static final String TAG = "MessageFragment";
    protected static final String PARAM_SHOW_TOP_BAR = "PARAM_SHOW_TOP_BAR";
    protected boolean shouldShowTopBar = true;
    private int page = 1;
    private int messageOffset = 0;
    private int limit = 30;
    private MessageAdapter mAdapter;
    private final List<Message> mMessage = new ArrayList<>();
    private int selectDeviceIndex = 0;
    private int selectDateIndex = 0;
    private int selectEventIndex = 0;
    private ImageView cameraTypeArrow;
    private boolean firstLoad = true;
    private LinearLayout llEmptyLayout;

    private Disposable serviceStatusDisposable;

    private PullLoadMoreRecyclerView pullLoadMoreRecyclerView;
    private RecyclerView mDateRecyclerView, mDeviceRecyclerView, mEventRecyclerView;
    private MessageFilterAdapter filterAdapter;
    private final List<DeviceItem> deviceItems = new ArrayList<>();
    private final List<MessageFilterBean> eventList = new ArrayList();
    private MessageDateAdapter messageDateAdapter;
    private MessageDeviceAdapter deviceDateAdapter;
    private MessageEventAdapter eventAdapter;
    private final List<WheelData> wheelData = new ArrayList<>();

    private View mDropDownLayout;
    private WheelData selectDay;

    protected View rootView;

    private TextView deviceName, deviceTime, deviceEvent;

    private DeviceListCallback deviceListCallback;

    public interface DeviceListCallback {
        List<DeviceItem> getDeviceList();
    }

    public void setDeviceListCallback(DeviceListCallback deviceListCallback) {
        this.deviceListCallback = deviceListCallback;
    }

    public static MessageFragment newInstance(Bundle bundle, boolean showTopBar) {
        MessageFragment fragment = new MessageFragment();
        Bundle b = bundle;
        if (b == null) {
            b = new Bundle();
        }
        b.putBoolean(PARAM_SHOW_TOP_BAR, showTopBar);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            shouldShowTopBar = getArguments().getBoolean(PARAM_SHOW_TOP_BAR, true);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rootView = inflater.inflate(R.layout.activity_messagenew, container, false);

        initView();

        return rootView;
    }

    private <T extends View> T findViewById(int id) {
        if (rootView == null) return null;
        return rootView.findViewById(id);
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initView() {
        llEmptyLayout = findViewById(R.id.ll_message_empty);
        mDeviceRecyclerView = findViewById(R.id.device_recycler_view);
        deviceName = findViewById(R.id.tv_message_filter_device_name);
        deviceEvent = findViewById(R.id.tv_message_filter_type);
        deviceTime = findViewById(R.id.tv_message_filter_date);
        int statusBarHeight = (int) safetyGetResources().getDimension(R.dimen.status_bar_height);
        int resourceId = safetyGetResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = safetyGetResources().getDimensionPixelSize(resourceId);
        }
        cameraTypeArrow = findViewById(R.id.tv_message_filter_device_name_arrow);
        LinearLayout linearLayout = findViewById(R.id.message_list_filter_toolbar);

        RelativeLayout.LayoutParams flp = (RelativeLayout.LayoutParams) linearLayout.getLayoutParams();
        flp.topMargin = statusBarHeight;
        linearLayout.setLayoutParams(flp);

        initDeviceData();

        pullLoadMoreRecyclerView = findViewById(R.id.pull_load_more_recyclerview);
        pullLoadMoreRecyclerView.setLinearLayout();
        mAdapter = new MessageAdapter(getActivity(), mMessage);
        pullLoadMoreRecyclerView.setAdapter(mAdapter);
        pullLoadMoreRecyclerView.setOnPullLoadMoreListener(this);

        mDateRecyclerView = findViewById(R.id.date_recycler_view);
        mDateRecyclerView.setBackgroundColor(safetyGetResources().getColor(R.color.white));
        LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getActivity());
        dateLayoutManager.setOrientation(RecyclerView.VERTICAL);
        this.mDateRecyclerView.setLayoutManager(dateLayoutManager);
        messageDateAdapter = new MessageDateAdapter(wheelData);
        this.mDateRecyclerView.setAdapter(messageDateAdapter);

        mDeviceRecyclerView.setBackgroundColor(safetyGetResources().getColor(R.color.white));
        LinearLayoutManager deviceLayoutManager = new LinearLayoutManager(getActivity());
        deviceLayoutManager.setOrientation(RecyclerView.VERTICAL);
        this.mDeviceRecyclerView.setLayoutManager(deviceLayoutManager);
        deviceDateAdapter = new MessageDeviceAdapter(deviceItems);
        deviceDateAdapter.setSelectedDay(0);
        this.mDeviceRecyclerView.setAdapter(deviceDateAdapter);
        deviceDateAdapter.setOnDateItemListener(position -> {
            hideDropdownLayout();
            if (selectDeviceIndex != position) {
                selectDeviceIndex = position;
                String str = deviceDateAdapter.getDateText(selectDeviceIndex);
                deviceName.setText(str);
                if (position == 0){
                    deviceName.setTextColor(ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_black));
                }else{
                    deviceName.setTextColor(ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_link));
                }
                messageOffset = 0;
                mMessage.clear();
                page = 1;
                getEvents();
            }
        });
        deviceDateAdapter.notifyDataSetChanged();
        mDropDownLayout = findViewById(R.id.drop_down_recycler_view_layout);
        mEventRecyclerView = findViewById(R.id.msg_type_recycler_view);
        mEventRecyclerView.setBackgroundColor(safetyGetResources().getColor(R.color.white));
        LinearLayoutManager eventLayoutManager = new LinearLayoutManager(getActivity());
        eventLayoutManager.setOrientation(RecyclerView.VERTICAL);
        this.mEventRecyclerView.setLayoutManager(eventLayoutManager);
        eventAdapter = new MessageEventAdapter(eventList);
        this.mEventRecyclerView.setAdapter(eventAdapter);
        eventAdapter.setOnDateItemListener(position -> {
            hideDropdownLayout();
            if (selectEventIndex != position) {
                selectEventIndex = position;
                page = 1;
                messageOffset = 0;
                mMessage.clear();
                String str = eventAdapter.getDateText(selectEventIndex);
                deviceEvent.setText(str);
                if (position == 0){
                    deviceEvent.setTextColor(ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_black));
                }else{
                    deviceEvent.setTextColor(ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_link));
                }
                getMessage();
            }
        });

        initDateList();

        mAdapter.setOnMessageItemListener(position -> {
            Message message = mMessage.get(position);
            Intent intent = new Intent();
            intent.setClass(mActivity, MessageFullScreenActivity.class);
            intent.putExtra(MessageFullScreenActivity.TAG_DEVICE_NAME, message.getEvent().getCategoryName());
            intent.putExtra(MessageFullScreenActivity.TAG_IMAGE_PATH, message.getImage());
            mActivity.startActivity(intent);
        });

        getEvents();

        findViewById(R.id.layout_message_filter_date).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDropDownLayout.getVisibility() == View.VISIBLE) {
                    mDropDownLayout.setVisibility(View.GONE);
                } else {
                    mDropDownLayout.setVisibility(View.VISIBLE);
                    mDateRecyclerView.setVisibility(View.VISIBLE);
                    mDeviceRecyclerView.setVisibility(View.GONE);
                    mEventRecyclerView.setVisibility(View.GONE);
                }
            }
        });

        findViewById(R.id.layout_message_filter_type).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDropDownLayout.getVisibility() == View.VISIBLE) {
                    mDropDownLayout.setVisibility(View.GONE);
                } else {
                    mDropDownLayout.setVisibility(View.VISIBLE);
                    mDateRecyclerView.setVisibility(View.GONE);
                    mDeviceRecyclerView.setVisibility(View.GONE);
                    mEventRecyclerView.setVisibility(View.VISIBLE);
                }
            }
        });


        findViewById(R.id.device_type_filter_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDropDownLayout.getVisibility() == View.VISIBLE) {
                    mDropDownLayout.setVisibility(View.GONE);
                } else {
                    mDropDownLayout.setVisibility(View.VISIBLE);
                    mDateRecyclerView.setVisibility(View.GONE);
                    mDeviceRecyclerView.setVisibility(View.VISIBLE);
                    mEventRecyclerView.setVisibility(View.GONE);
                    cameraTypeArrow.setImageResource(R.drawable.ic_tange_message_up);
                }
            }
        });
    }


    private void initDeviceData() {
        List<DeviceItem> list = deviceListCallback.getDeviceList();
        deviceItems.clear();
        if (list != null && list.size() > 0) {
            deviceItems.addAll(list);
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    private void initDateList() {
        int DAY_OF_AGO = 30;
        String[] weeks = safetyGetResources().getStringArray(R.array.calendar_weeks);
        for (int i = 0; i < DAY_OF_AGO; i++) {
            WheelData data = new WheelData();
            data.status = 1;
            int weekIndex = DateUtil.getDayOffWeek(i, TimeZone.getDefault()) - 1;
            data.week = weeks[weekIndex];
            String day = DateUtil.getLastSomeDate(i, TimeZone.getDefault());
            data.date = day;
            wheelData.add(data);

        }
        selectDay = wheelData.get(0);
        String text = MessageDateAdapter.getDateText(selectDay);
        deviceTime.setText(text);
        messageDateAdapter.setSelectedDay(0);
        messageDateAdapter.notifyDataSetChanged();
        mDateRecyclerView.scrollToPosition(0);
        messageDateAdapter.setOnDateItemListener(position -> {
            hideDropdownLayout();
            if (selectDateIndex != position) {
                selectDateIndex = position;
                selectDay = wheelData.get(position);
                String str = MessageDateAdapter.getDateText(selectDay);
                deviceTime.setText(str);
                page = 1;
                messageOffset = 0;
                mMessage.clear();
                pullLoadMoreRecyclerView.setRefreshing(true);
                pullLoadMoreRecyclerView.scrollToTop();
                getMessage();
            }
        });
    }

    private void hideDropdownLayout() {
        mDropDownLayout.setVisibility(View.GONE);
        mDateRecyclerView.setVisibility(View.GONE);
        mDeviceRecyclerView.setVisibility(View.GONE);
        mEventRecyclerView.setVisibility(View.GONE);
    }

    private void getEvents() {
        eventList.clear();
        DeviceItem deviceItem = null;
        if (selectDeviceIndex > 0) {
            deviceItem = deviceItems.get(selectDeviceIndex - 1);
        }

        final List<DeviceItem> devList = new ArrayList<>();
        devList.addAll(deviceItems);
        if (deviceItem != null) {
            devList.clear();
            devList.add(deviceItem);
        }

        List<String> deviceList = new ArrayList<>();
        for (DeviceItem item : devList) {
            deviceList.add(item.uuid);
        }

        MessageFilterBean filterBean = new MessageFilterBean();
        filterBean.id = 0;
        filterBean.name = safetyGetResources().getString(R.string.message_filter_type_all);
        filterBean.event = EventConstants.ALL;
        eventList.add(filterBean);
        eventAdapter.setSelectedDay(0);
        eventAdapter.notifyDataSetChanged();

        if (deviceList.size() == 0) {
            pullLoadMoreRecyclerView.setRefreshing(false);
        }else{
            pullLoadMoreRecyclerView.setRefreshing(true);
            CloudMessage.INSTANCE.queryMessageCategory(deviceList, listResp -> {
                if (listResp.getSuccess()) {
                    if (!isActivityValid()) return;
                    List<MessageCategory> content = listResp.getData();
                    TGLog.i(TAG, "[getMessageFilter] onSuccess ...");
                    if (content != null && content.size() > 0) {
                        for (MessageCategory bean : content) {
                            TGLog.i(TAG, "[getMessageFilter] onSuccess get " + bean.getCategoryLabel() + " ==> " + bean.getCategoryName() + " | " + bean.getCategoryType());
                            MessageFilterBean messageFilterBean = new MessageFilterBean();
                            messageFilterBean.id = 0;
                            messageFilterBean.name = bean.getCategoryName();
                            messageFilterBean.event = bean.getCategoryLabel();
                            eventList.add(messageFilterBean);
                        }

                        eventAdapter.notifyDataSetChanged();
                        getMessage();
                    } else {
                        TGLog.i(TAG, "[getMessageFilter] onSuccess EMPTY");
                        pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        decideToShowWitch(true);
                    }
                } else {
                    if (!isActivityValid()) return;
                    TGLog.i(TAG, "[getMessageFilter] onError = " + listResp.getMessage());
                    if (listResp.getCode() == 401) {
                        LogoutDialogHelper.getInstance().showLogoutDialog(null);
                    } else {
                        TGToast.showToast("Error on request filter: errorCode = " + listResp.getMessage());
                    }

                }
            });
        }
    }

    private void getMessage() {
        List<String> deviceList = new ArrayList<>();
        DeviceItem device = null;
        if (selectDeviceIndex > 0) {
            device = deviceItems.get(selectDeviceIndex - 1);
        }
        if (device != null) {
            deviceList.add(device.uuid);
        }else{
           for (DeviceItem deviceItem : deviceItems){
               deviceList.add(deviceItem.uuid);
           }
        }

        String today = DateUtil.getTodayDate();
        if (selectDay != null && !TextUtils.equals(selectDay.date, safetyGetResources().getString(R.string.playback_today))) {
            today = selectDay.date;
        }

        ArrayList<String> list = new ArrayList<>();
        list.addAll(eventAdapter.getEvent());

        CloudMessage.INSTANCE.queryMessageByDate(deviceList, today, list, messageOffset, limit, messageByPaginationResp -> {
            TGLog.i(TAG, "[getMessage] onSuccess : messageByPaginationResp = " + messageByPaginationResp);
            pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
            if (messageByPaginationResp != null && messageByPaginationResp.getSuccess()) {
                firstLoad = false;
                MessageByPagination content = messageByPaginationResp.getData();
                if (content != null) {
                    List<Message> items = content.getMessages();
                    if (items != null) {
                        TGLog.i(TAG, "[getMessage] onSuccess :    item = " + items.size());
                        messageOffset += items.size();
                        mMessage.addAll(items);
                        if (mMessage.size() > 0) {
                            decideToShowWitch(false);
                        } else {
                            decideToShowWitch(true);
                        }
                    }else{
                        decideToShowWitch(true);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            }else{
                if (messageByPaginationResp != null && messageByPaginationResp.getCode() == 401) {
                    LogoutDialogHelper.getInstance().showLogoutDialog(null);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseDisposable();
    }

    private boolean isActivityValid() {
        if (getActivity() == null) return  false;
        if (getActivity().isFinishing() || getActivity().isDestroyed()) return false;

        return true;
    }

    private void decideToShowWitch(boolean noData) {
        TGLog.i(TAG, "decideToShowWitch: noData = " + noData);
        if (noData) {
            showEventListInternal();
        } else {
            llEmptyLayout.setVisibility(View.GONE);
            pullLoadMoreRecyclerView.setVisibility(View.VISIBLE);
            releaseDisposable();
        }
    }

    private void releaseDisposable() {
        try {
            if (serviceStatusDisposable != null && !serviceStatusDisposable.isDisposed()) {
                serviceStatusDisposable.dispose();
            }
            serviceStatusDisposable = null;
        } catch (Throwable ex) {

        }
    }

    public static boolean isContains(String attr, String key, String val){
        if (StringUtils.isEmpty(attr)){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(attr);
        if (jsonObject != null){
            String power = jsonObject.getString(key);
            return StringUtils.equalsIgnoreCase(power, val);
        }
        return false;
    }

    private void showEventListInternal() {
        if (!isActivityValid()) return;
        if (pullLoadMoreRecyclerView != null) {
            pullLoadMoreRecyclerView.post(() -> llEmptyLayout.setVisibility(mMessage.size() > 0? View.GONE : View.VISIBLE));
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!firstLoad){
            if (!hidden) {
                initDeviceData();
                getMessage();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        TGLog.i(TAG, "[onResume] firstLoad = " + firstLoad);

        if (!firstLoad) {
            TGLog.i(TAG, "[onResume] not first load, current list size = " + mMessage.size());
            if (mMessage.size() < 1) {
                TGLog.i(TAG, "[onResume] try to reload message list");
                page = 1;
                messageOffset = 0;
                mMessage.clear();
                getMessage();
            }
        }
    }


    @Override
    public void onRefresh() {
        TGLog.i(TAG, "[onRefresh]");
        page = 1;
        messageOffset = 0;
        mMessage.clear();
        getMessage();
    }

    @Override
    public void onLoadMore() {
        TGLog.i(TAG, "[onLoadMore]");
        getMessage();
    }

}
